<template>
  <div>
    <!-- 头部 -->
    <div class="plantion">
      <span>
        时间段：
        <el-select v-model="period" placeholder="全部" style="width: 220px" @change="selectPlan()">
          <el-option v-for="item in options" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </span>
      &#12288;
      <span class="btn-plan">
        <!-- <el-button type="primary" @click="selectPlan()">查询</el-button> -->
        <el-button type="primary" @click="releasePlan()">发布计划</el-button>
      </span>
    </div>
    <br />

    <!-- 表格 -->
    <div>
      <el-table :data="tableData" border style="width: 100%" ref="planTable" :cell-style="cellStayle">
        <el-table-column type="index" align="center" label="序号" width="50">
        </el-table-column>
        <el-table-column prop="weekPartStr" align="center" label="计划日期" width="200">
        </el-table-column>
        <el-table-column prop="planWeek" align="center" label="周显示" width="100">
          <template slot-scope="scope">
            <span>第{{ scope.row.planWeek }}周</span>
          </template>
        </el-table-column>
        <el-table-column prop="projectName" align="center" label="项目" width="200">
        </el-table-column>
        <el-table-column prop="planMsg" header-align="center" label="内容" width="400">
        </el-table-column>
        <el-table-column prop="pushTime" align="center" label="发布时间" width="200">
        </el-table-column>
        <el-table-column prop="planFlag" align="center" label="星标" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.planFlag == 0 ? "未星标" : "已星标" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="planPercentage" align="center" label="完成百分比" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.planPercentage }}<span v-if="scope.row.planPercentage != null">%</span></span>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" align="center" label="备注" width="200">
        </el-table-column>
        <el-table-column prop="operation" align="center" label="操作" fixed="right" width="300">
          <template slot-scope="scope">
            <!-- <el-checkbox
              v-model="checked"
              @change="box(scope.row)"
            ></el-checkbox> -->
            <el-button type="primary" plain size="mini" @click="updatePlan(scope.row)">修 改</el-button>
            <el-button type="primary" plain size="mini" @click="recordPlan(scope.row)"
              v-if="scope.row.planPercentage == null">记 录</el-button>
            <el-button type="danger" plain size="mini" @click="deletePlan(scope.row)">删 除</el-button>
            <el-button type="success" plain size="mini" @click="box(scope.row)">
              {{ scope.row.planFlag == 0 ? "星标" : "取消星标" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination background layout="total, sizes, prev, pager, next, jumper" v-if="pageObj"
        :page-size="pageObj.size" :total="pageObj.total" :current-page="pageObj.currentPage"
        @current-change="pageObj.func" @size-change="handleSizeChange" :page-sizes="[5, 10, 15, 20, 30, 40]">
      </el-pagination>
    </div>

    <!-- 发布计划的对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormPlan" center width="40%" :close-on-click-modal="false">
      <el-form :model="form" ref="form" :rules="rules">
        <el-form-item label="计划日期:" :label-width="formLabelWidth" v-if="this.category == 'add'" prop="weekPartStr"
          :rules="{
            required: true,
            message: '计划时间不能为空',
            trigger: 'blur',
          }">
          <el-select v-model="form.weekPartStr" placeholder="请选择" style="width: 70%">
            <el-option v-for="item in options" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计划日期:" :label-width="formLabelWidth" v-if="this.category == 'update'">
          <el-select v-model="perioddialog" placeholder="请选择" style="width: 70%">
            <el-option v-for="item in options" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <div v-if="this.category == 'add'">
          <el-form-item v-for="(item, i) of form.planMsgs" :key="i">
            <el-form-item label="计划项目" :label-width="formLabelWidth" :prop="`planMsgs[${i}].project`" :rules="{
              required: true,
              message: '请选择项目',
              trigger: 'blur'
            }">
              <el-select v-model="item.project" placeholder="请选择项目" filterable style="width: 70%">
                <el-option v-for="item in projects" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <p></p>
            <el-form-item label="计划内容" :prop="'planMsgs.' + i + '.value'" :label-width="formLabelWidth" :rules="{
              required: true,
              message: '计划内容不能为空',
              trigger: 'blur',
            }">
              <el-input style="width: 70%" type="textarea" v-model="item.value">
              </el-input>
              <el-button icon="el-icon-minus" circle @click="dele(item)"></el-button>
            </el-form-item>
          </el-form-item>

          <!-- </el-form-item> -->
          <div class="btn-input">
            <el-button icon="el-icon-plus" circle @click="add()"></el-button>
          </div>
        </div>
        <div v-if="this.category == 'update'">
          <el-form-item label="计划项目" :label-width="formLabelWidth">
            <el-select v-model="planProdialog" placeholder="请选择项目" filterable style="width: 70%">
              <el-option v-for="item in projects" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="计划内容:" :label-width="formLabelWidth" :prop="planMsg">
            <el-input style="width: 70%" type="textarea" v-model="planMsgdialog">
            </el-input>
          </el-form-item>
        </div>
        <el-form-item label="完成百分比:" :label-width="formLabelWidth" style="width: 70%;" v-if="tab == 1"
          prop="planPercentage">
          <el-input v-model="form.planPercentage" placeholder="请输入内容" style="width: 90%;"></el-input>&#12288;%
        </el-form-item>
        <el-form-item label="备注:" :label-width="formLabelWidth" style="width: 70%;" v-if="tab == 1">
          <el-input v-model="form.remarks" placeholder="请输入内容" maxlength="32" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="submitPlanAdd('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  companyPlan,
  companyPlanList,
  addCompanyPlan,
  updateCompanyPlan,
  deleteCompanyPlan,
  showState,
  getCompanyProject,
} from "@/service/Api.js"; //接口
export default {
  data() {
    let valid = (rule, value, callback) => {
      if (value) {
        var timeformat = /(^(\d|[1-9]\d)(\.\d{1,2})?$)|(^100$)/
        if (!timeformat.test(value)) {
          callback(new Error("请输入0-100的数字"))
        } else {
          callback()
        }
      }
    }
    return {
      flag: true,
      type: 0,
      period: "",
      perioddialog: "",
      tableData: [],
      pageObj: {
        size: 10,
        total: 0,
        height: "75vh",
        currentPage: 1,
        func: (currentPage) => {
          this.pageTurning(currentPage);
        },
      },
      id: "",
      pn: 1,
      ps: 10,
      form: {
        weekPartStr: "",
        planMsgs: [{ project: "", value: "" }],
        planPercentage: "",
        remarks: ""
      },
      arrPlanMsgs: [],
      arrProjects: [],
      options: [],
      checked: false,
      planFlag: "",
      title: "",
      dialogFormPlan: false,
      formLabelWidth: "150px",
      //value1: "",
      content: "",
      weekPartStr: "",
      planMsg: "",
      planMsgdialog: "",
      planProdialog: "",
      planPro: "",
      inputDataNum: 0,
      category: "",
      rules: {
        planPercentage: [
          { required: true, message: "请输入完成百分比", trigger: "blur" },
          { required: true, validator: valid, trigger: "blur" },
        ],
        // planMsgs: [
        //   { required: true, message: "请输入计划内容", trigger: "blur" },
        // ],
      },
      projects: [],
      tab: 0
    };
  },

  created() {
    this.weekDate();
  },
  methods: {
    //获取周计划时间段
    weekDate() {
      if (this.type == 1) {
        companyPlan((this.type = 1)).then((res) => {
          //console.log(res);
          if (res.code == 0) {
            this.options = res.data;
            this.form.weekPartStr = res.data[0];
          }
        });
      } else if (this.type == 0) {
        companyPlan((this.type = 0)).then((res) => {
          //console.log(res);
          if (res.code == 0) {
            this.options = res.data;
            if (this.period == "") {
              this.period = res.data[3];
            }
            this.options.unshift("全部");
            this.dataList();
          }
        });
      } else {
        companyPlan((this.type = -1)).then((res) => {
          //console.log(res);
          if (res.code == 0) {
            this.options = res.data;
            // this.period = "全部";
            if (this.period == "") {
              this.period = res.data[0];
            }
          }
        });
      }
    },
    //查询
    selectPlan() {
      this.type = 0;
      this.weekDate();
    },

    //获取公司周计划项目
    getWeekProject() {
      getCompanyProject().then(res => {
        if (res.code == 0) {
          this.projects = res.data
        }
      })
    },

    dataList() {
      if (this.period == "全部") {
        let data = {
          planDateStr: "",
          pn: this.pn,
          ps: this.ps,
        };
        companyPlanList(data).then((res) => {
          console.log(res);
          this.tableData = res.data.records;
          this.pageObj.total = res.data.total;
          this.pageObj.currentPage = res.data.current;
          this.pageObj.size = res.data.size;
          //loading.close();
        });
      } else {
        let data = {
          planDateStr: this.period,
          pn: this.pn,
          ps: this.ps,
        };
        companyPlanList(data).then((res) => {
          console.log(res);
          this.tableData = res.data.records;
          this.pageObj.total = res.data.total;
          this.pageObj.currentPage = res.data.current;
          this.pageObj.size = res.data.size;
          //loading.close();
        });
      }
    },
    //翻页
    pageTurning(currentPage) {
      this.pageObj.currentPage = currentPage;
      this.pn = currentPage;
      this.dataList();
    },

    handleSizeChange(val) {
      this.ps = val;
      this.dataList();
    },

    //表格百分比颜色设置
    cellStayle(row, column, rowIndex, columnIndex) {
      if (row.column.label == '完成百分比') {
        if (row.row.planPercentage > 0 && row.row.planPercentage < 50) {
          return "background: red;color:black";
        } else if (row.row.planPercentage >= 50 && row.row.planPercentage < 70) {
          return "background: yellow;color:black";
        } else if (row.row.planPercentage >= 70 && row.row.planPercentage < 100) {
          return "background: #409EFF;color:black";
        } else if (row.row.planPercentage == 100) {
          return "background: rgb(0, 185, 141);color:black";
        }
      }
    },

    //打开发布计划窗口
    releasePlan() {
      this.category = "add";
      this.title = "发布计划";
      this.form.weekProject = "";
      this.type = 1;
      this.weekDate();
      this.getWeekProject();
      this.dialogFormPlan = true;
    },

    //新增公司周计划
    submitPlanAdd(form) {
      if (this.category == "add") {
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.arrPlanMsgs = []
            this.arrProjects = []
            for (let i in this.form.planMsgs) {
              this.arrPlanMsgs.push(this.form.planMsgs[i].value);
              this.arrProjects.push(this.form.planMsgs[i].project);
            }
            //this.weekPartStr = this.form.weekPartStr;
            let data = {
              weekPartStr: this.form.weekPartStr,
              planMsgs: this.arrPlanMsgs,
              projectIds: this.arrProjects,
            };
            addCompanyPlan(data).then((res) => {
              if (res.code == 0) {
                this.$message({
                  message: res.message,
                  type: "success",
                });
                this.cancel();
                this.selectPlan();
              } else {
                this.$message({
                  message: res.message,
                  type: "warning",
                });
              }
            });
          }
        });
      } else if (this.category == "update") {
        this.$refs[form].validate((valid) => {
          if (valid) {
            if (this.planMsgdialog == "") {
              this.$message({
                message: "计划内容不能为空",
                type: "warning",
              });
            } else {
              let data = {
                id: this.id,
                weekPartStr: this.perioddialog,
                planMsg: this.planMsgdialog,
                projectId: this.planPro,
                planPercentage: this.form.planPercentage,
                remarks: this.form.remarks,
              };
              updateCompanyPlan(data, 0).then((res) => {
                if (res.code == 0) {
                  this.$message({
                    message: res.message,
                    type: "success",
                  });
                } else {
                  this.$message({
                    message: res.message,
                    type: "warning",
                  });
                }
                this.cancel();
                this.selectPlan();
                this.dialogFormPlan = false;
              });
            }
          }
        });
      } else {
        let data = {
          id: this.id,
          planPercentage: this.form.planPercentage,
          remarks: this.form.remarks,
        };
        updateCompanyPlan(data, 1).then((res) => {
          if (res.code == 0) {
            this.$message({
              message: res.message,
              type: "success",
            });
            this.cancel();
            this.selectPlan();
            this.dialogFormPlan = false;
          } else {
            this.$message({
              message: res.message,
              type: "warning",
            });
          }
        });
      }
      //this.clear();
    },
    add() {
      this.form.planMsgs.push({ project: "", value: "" });
    },
    dele(item) {
      if (this.form.planMsgs.length === 1) {
        this.$message({
          message: "至少一条计划",
          type: "warning",
        });
      } else {
        var index = this.form.planMsgs.indexOf(item);
        if (index !== -1) {
          this.form.planMsgs.splice(index, 1);
        }
      }
    },

    //打开修改计划窗口
    updatePlan(row) {
      this.category = "update";
      this.title = "修改计划";
      this.type = 1;
      this.weekDate();
      this.perioddialog = row.weekPartStr;
      this.planMsgdialog = row.planMsg;
      this.planProdialog = row.projectName;
      this.planPro = row.projectId;
      this.form.remarks = row.remarks;
      this.form.planPercentage = row.planPercentage;
      this.getWeekProject();
      this.id = row.id;
      if (row.planPercentage == null) {
        this.tab = 0
      } else {
        this.tab = 1
      }
      this.dialogFormPlan = true;
    },

    //打开记录窗口
    recordPlan(row) {
      this.category = "record";
      this.title = "公司计划记录";
      this.id = row.id;
      this.tab = 1;
      this.dialogFormPlan = true;
    },

    //删除计划
    deletePlan(row) {
      this.$confirm("是否删除此计划?", "删除计划", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          this.id = row.id;
          deleteCompanyPlan(this.id).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.selectPlan();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    box(row) {
      if (row.planFlag == 0) {
        let data = {
          id: row.id,
          flag: 1,
        };
        showState(data).then((res) => {
          this.$message({
            type: "success",
            message: "星标!",
          });
          this.selectPlan();
        });
      } else {
        let data = {
          id: row.id,
          flag: 0,
        };
        showState(data).then((res) => {
          this.$message({
            type: "success",
            message: "取消星标!",
          });
          this.selectPlan();
        });
      }
    },

    cancel() {
      this.tab = 0;
      this.arrPlanMsgs = [];
      this.form.planMsgs = [{ value: "" }];
      this.form.remarks = "";
      this.form.planPercentage = "";
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
      this.selectPlan();
      this.dialogFormPlan = false;
    },
  },
};
</script>

<style>
.plantion {
  display: flex;
}

.btn-plan {
  float: left;
}

.btn-input {
  line-height: 60px;
  text-align: center;
  width: 500px;
}
</style>
